import express, { Request, Response } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import bodyParser from 'body-parser';

import config from './config/config';
import userRoutes from './routes/userRoutes';
import authRoutes from './routes/authRoutes';
import roleRoutes from './routes/roleRoutes';
import errorHandler from './middleware/errorHandler';
import notFound from './middleware/notFound';
import { UserRole, RoleDisplayNames, RolePermissions } from './consts/role';

const app = express();

// 安全中间件
app.use(helmet());

// CORS 配置
app.use(cors({
  origin: "*",
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 日志中间件
if (config.NODE_ENV === 'development') {
  app.use(morgan('dev'));
} else {
  app.use(morgan('combined'));
}

// 解析请求体
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));

// 健康检查
app.get('/health', (req: Request, res: Response) => {
  res.json({
    success: true,
    message: '服务器运行正常',
    timestamp: new Date().toISOString(),
    environment: config.NODE_ENV,
    version: '1.0.0'
  });
});

// 根路径
app.get('/', (req: Request, res: Response) => {
  res.json({
    message: '🎉 欢迎使用 Node.js RESTful API (TypeScript)',
    version: '1.0.0',
    environment: config.NODE_ENV,
    endpoints: {
      health: '/health',
      users: '/api/users',
      auth: '/api/auth',
      docs: '/api/docs'
    },
    documentation: '/api/docs'
  });
});

// API 路由
app.use('/api/users', userRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/roles', roleRoutes);

// API 文档路径
app.get('/api/docs', (req: Request, res: Response) => {
  res.json({
    title: 'Node.js RESTful API 文档 (TypeScript)',
    version: '1.0.0',
    description: '基于 Express.js + TypeScript 构建的 RESTful API 服务',
    baseUrl: `http://localhost:${config.PORT}`,
    endpoints: [
      {
        group: '系统',
        routes: [
          { path: '/', method: 'GET', description: '获取API基本信息' },
          { path: '/health', method: 'GET', description: '健康检查' }
        ]
      },
      {
        group: '用户管理',
        routes: [
          { path: '/api/users', method: 'GET', description: '获取所有用户列表', permission: '需要管理员权限' },
          { path: '/api/users/:id', method: 'GET', description: '根据ID获取单个用户', permission: '无需特殊权限' },
          { path: '/api/users', method: 'POST', description: '创建新用户', permission: '需要管理员权限' },
          { path: '/api/users/:id', method: 'PUT', description: '更新用户信息', permission: '需要用户更新权限' },
          { path: '/api/users/:id', method: 'DELETE', description: '删除用户', permission: '需要管理员权限' }
        ]
      },
      {
        group: '认证',
        routes: [
          { path: '/api/auth/register', method: 'POST', description: '用户注册' },
          { path: '/api/auth/login', method: 'POST', description: '用户登录' },
          { path: '/api/auth/me', method: 'GET', description: '获取当前用户信息' },
          { path: '/api/auth/logout', method: 'POST', description: '用户登出' }
        ]
      },
      {
        group: '角色管理',
        routes: [
          { path: '/api/roles', method: 'GET', description: '获取所有可用角色' },
          { path: '/api/roles/stats', method: 'GET', description: '获取角色统计信息' },
          { path: '/api/roles/:role/users', method: 'GET', description: '根据角色获取用户列表' },
          { path: '/api/roles/users/:userId/permission', method: 'GET', description: '检查用户权限' },
          { path: '/api/roles/compare', method: 'GET', description: '比较两个角色权限' }
        ]
      }
    ],
    features: [
      '✅ TypeScript 类型安全',
      '✅ RESTful API 设计规范',
      '✅ 用户管理 CRUD 操作',
      '✅ 用户认证（登录/注册）',
      '✅ 基于枚举的角色权限系统',
      '✅ 错误处理中间件',
      '✅ 请求日志记录',
      '✅ CORS 跨域支持',
      '✅ 数据验证',
      '✅ 环境配置管理'
    ],
    roles: {
      available: Object.values(UserRole),
      displayNames: RoleDisplayNames,
      permissions: RolePermissions
    }
  });
});

// 404 处理
app.use(notFound);

// 错误处理中间件
app.use(errorHandler);

export default app;
